package com.dexafree.materiallist.view;


import com.dexafree.materiallist.AttrUtils;
import com.dexafree.materiallist.ResourceTable;
import com.dexafree.materiallist.card.Card;
import com.dexafree.materiallist.listeners.OnDismissCallback;
import com.dexafree.materiallist.listeners.RecyclerItemClickListener;
import com.dexafree.materiallist.listeners.SwipeDismissRecyclerViewTouchListener;
import ohos.agp.components.*;
import ohos.agp.database.DataSetSubscriber;
import ohos.app.Context;
import ohos.data.rdb.DataObservable;
import ohos.data.rdb.DataObserver;
import ohos.global.configuration.Configuration;
import ohos.hiviewdfx.HiLog;
import utils.LogUtil;


public class MaterialListView extends ListContainer {

    private static final int DEFAULT_COLUMNS_PORTRAIT = 1;
    private static final int DEFAULT_COLUMNS_LANDSCAPE = 2;

    private OnDismissCallback mDismissCallback;
    private SwipeDismissRecyclerViewTouchListener mDismissListener;
    private Component mEmptyView;
    private int mColumnCount;
    private int mColumnCountLandscape = DEFAULT_COLUMNS_LANDSCAPE;
    private int mColumnCountPortrait = DEFAULT_COLUMNS_PORTRAIT;
    private final DataSetSubscriber mEmptyViewObserver = new DataSetSubscriber() {
        @Override
        public void onChanged() {
            super.onChanged();
            checkIfEmpty();
        }
    };

    public MaterialListView(Context context) {
        this(context, null);
    }

    public MaterialListView(Context context, AttrSet attrs) {
        this(context, attrs, null);
    }

    public MaterialListView(Context context, AttrSet attrs, String styleName) {
        super(context, attrs, styleName);

        mDismissListener = new SwipeDismissRecyclerViewTouchListener(this,
                new SwipeDismissRecyclerViewTouchListener.DismissCallbacks() {
                    @Override
                    public boolean canDismiss(final int position) {
                        final Card card = getItemProvider().getCard(position);
                        return card != null && card.isDismissible();
                    }

                    @Override
                    public void onDismiss(final ListContainer recyclerView,
                                          final int[] reverseSortedPositions) {
                        for (int reverseSortedPosition : reverseSortedPositions) {
                            final Card card = getItemProvider().getCard(reverseSortedPosition);
                            if (card != null) {
                                getItemProvider().remove(card, false);
                                if (mDismissCallback != null) {
                                    mDismissCallback.onDismiss(card, reverseSortedPosition);
                                }
                            }
                        }
                    }
                });
        setTouchEventListener(mDismissListener);
        addScrolledListener(mDismissListener.makeScrollListener());

        MaterialListAdapter adapter = new MaterialListAdapter(new OnSwipeAnimation() {
            @Override
            public void animate(final int position) {
//                ComponentHolder holder = findComponentHolderById(position);
                Component component = getComponentAt(position);
                if (component != null) {
                    mDismissListener.dismissCard(component, position);
                }
            }
        }, new OnAdapterItemsChanged() {
            @Override
            public void onAddItem(int position, boolean scroll) {
                if (scroll) {
                    scrollTo(position);
                }
                checkIfEmpty();
            }

            @Override
            public void onRemoveItem() {
                checkIfEmpty();
            }
        });
        setAdapter(adapter);

        if (attrs != null) {
            // get the number of columns

            mColumnCount = AttrUtils.getInteger(attrs, "column_count", 0);
            if (mColumnCount > 0) {
                mColumnCountPortrait = mColumnCount;
                mColumnCountLandscape = mColumnCount;
            } else {
                mColumnCountPortrait = AttrUtils.getInteger(
                        attrs, "column_count_portrait",
                        DEFAULT_COLUMNS_PORTRAIT);
                mColumnCountLandscape = AttrUtils.getInteger(
                        attrs, "column_count_landscape",
                        DEFAULT_COLUMNS_LANDSCAPE);
            }

            boolean isLandscape = isLandscape();
            mColumnCount = isLandscape ? mColumnCountLandscape : mColumnCountPortrait;
            setColumnLayout(mColumnCount);


        }
    }

    public <T extends MaterialListAdapter> void setAdapter(final T adapter) {
        final BaseItemProvider oldAdapter = getItemProvider();
        if (oldAdapter != null) {
            oldAdapter.removeDataSubscriber(mEmptyViewObserver);
        }
        super.setItemProvider(adapter);
        adapter.addDataSubscriber(mEmptyViewObserver);
    }

    @Override
    public MaterialListAdapter getItemProvider() {
        return (MaterialListAdapter) super.getItemProvider();
    }

    public int getColumnCount() {
        return mColumnCount;
    }

    public void setColumnCount(int columnCount) {
        mColumnCount = columnCount;
    }

    public int getColumnCountLandscape() {
        return mColumnCountLandscape;
    }

    public void setColumnCountLandscape(int columnCountLandscape) {
        mColumnCountLandscape = columnCountLandscape;
    }

    public int getColumnCountPortrait() {
        return mColumnCountPortrait;
    }

    public void setColumnCountPortrait(int columnCountPortrait) {
        mColumnCountPortrait = columnCountPortrait;
    }

    public void setOnDismissCallback(OnDismissCallback callback) {
        mDismissCallback = callback;
    }

    public void setEmptyView(Component emptyView) {
        mEmptyView = emptyView;
        checkIfEmpty();
    }

    public void addOnItemTouchListener(RecyclerItemClickListener.OnItemClickListener listener) {
        RecyclerItemClickListener itemClickListener =
                new RecyclerItemClickListener(getContext(), listener);
        itemClickListener.setRecyclerView(this);
        setItemClickedListener(itemClickListener);
    }

//    @Override
//    protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh) {
//        super.onSizeChanged(w, h, oldw, oldh);
//
//        boolean isLandscape = isLandscape();
//        int newColumnCount = isLandscape ? mColumnCountLandscape : mColumnCountPortrait;
//        if (mColumnCount != newColumnCount) {
//            mColumnCount = newColumnCount;
//            setColumnLayout(mColumnCount);
//        }
//    }

    private void setColumnLayout(int columnCount) {
        if (columnCount > 1) {
            TableLayoutManager tableLayoutManager = new TableLayoutManager();
            tableLayoutManager.setOrientation(TableLayout.VERTICAL);
            setLayoutManager(tableLayoutManager);
        } else {
            DirectionalLayoutManager directionalLayoutManager = new DirectionalLayoutManager();
            directionalLayoutManager.setOrientation(DirectionalLayout.VERTICAL);
            setLayoutManager(directionalLayoutManager);
        }
    }

    private boolean isLandscape() {
        return getContext().getResourceManager().getConfiguration().direction == Configuration.DIRECTION_HORIZONTAL;
    }

    private void checkIfEmpty() {
        if (mEmptyView != null) {
            mEmptyView.setVisibility(getItemProvider().isEmpty() ? VISIBLE : HIDE);
            setVisibility(getItemProvider().isEmpty() ? HIDE : VISIBLE);
        }
    }

    /**
     *
     */
    interface OnSwipeAnimation {
        /**
         * @param position
         */
        void animate(final int position);
    }

    /**
     *
     */
    interface OnAdapterItemsChanged {
        /**
         * @param position
         * @param scroll
         */
        void onAddItem(final int position, boolean scroll);

        /**
         *
         */
        void onRemoveItem();
    }
}
